package com.bluefox.uac.filter;


import com.bluefox.uac.exception.VerificationCodeException;
import com.bluefox.uac.handler.MyAuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 拦截图片验证 使用过滤器完成图片验证
 * @author Administrator
 */
public class VerificationCodeFilter extends OncePerRequestFilter {
    private MyAuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (!"/auth/form".equals(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            verificationCode(httpServletRequest, httpServletResponse);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }

    protected void verificationCode(HttpServletRequest request, HttpServletResponse response) throws VerificationCodeException {
        String requestCode = request.getParameter("captcha");
        HttpSession session = request.getSession();
        String saveCode = (String) session.getAttribute("captcha");

        if (!StringUtils.isEmpty(saveCode)) {
            session.removeAttribute("captcha");
        }
        if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(saveCode) || !requestCode.equals(saveCode)) {
            throw new VerificationCodeException();
        }
    }
}
